package org.saratogaschools.edd.firefighter.client.activity;

import org.saratogaschools.edd.firefighter.client.ClientFactory;
import org.saratogaschools.edd.firefighter.client.place.AddDepartmentPlace;
import org.saratogaschools.edd.firefighter.client.place.SelectRolePlace;
import org.saratogaschools.edd.firefighter.client.util.AsyncPlaceChange;
import org.saratogaschools.edd.firefighter.client.view.AddDepartmentView;
import org.saratogaschools.edd.firefighter.shared.model.Department;
import org.saratogaschools.edd.firefighter.shared.model.FireFighter;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class AddDepartmentActivity extends AbstractActivity implements
		AddDepartmentView.Presenter {

	private FireFighter registrationCandidate;
	private ClientFactory clientFactory;

	public AddDepartmentActivity(AddDepartmentPlace place,
			ClientFactory clientFactory) {
		this.registrationCandidate = place.getRegistrationCandidate();
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		AddDepartmentView view = new AddDepartmentView();
		view.setPresenter(this);
		panel.setWidget(view);
	}

	@Override
	public void addDepartment(String name) {
		Department department = new Department();
		department.setName(name);
		clientFactory.getService().addDepartment(department, new AddDepartmentCallback());
	}
	
	private class AddDepartmentCallback implements AsyncCallback<Department> {
		@Override
		public void onFailure(Throwable caught) {}
		
		public void onSuccess(Department result) {
			String departmentKey = result.getEncodedKey();
			registrationCandidate.setDepartmentKey(departmentKey);
			GWT.runAsync(new AsyncPlaceChange(clientFactory, new SelectRolePlace(registrationCandidate)));
		}
	}
}
